import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    //通过重写run，描述执行的任务
    private Runnable runnable;
    //执行任务的时间，这里使用绝对时间
    private long time;

    public MyTimerTask(Runnable runnable, long time) {
        this.runnable = runnable;
        //传入的是相对时间,这里计算绝对时间
        this.time = System.currentTimeMillis() + time;
    }

    public long getTime() {
        return time;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer{
    private PriorityQueue<MyTimerTask> priorityQueue = new PriorityQueue<>();
    private Object locker = new Object();

    public void schedule(Runnable runnable, long time){
        synchronized (locker){
            priorityQueue.offer(new MyTimerTask(runnable, time));
            locker.notify();
        }
    }

    public MyTimer() {
        Thread thread = new Thread(() -> {
            //扫描线程，需要不停的扫描队首元素，看是否到达时间
            while(true){
                synchronized (locker){
                    //如果当前没有任务，阻塞等待
                    while(priorityQueue.isEmpty()){
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    //判断是否到执行时间了
                    long curTime = System.currentTimeMillis();
                    MyTimerTask task = priorityQueue.peek();
                    if(curTime >= task.getTime()){
                        //执行完任务，并删除队首元素
                        task.getRunnable().run();
                        priorityQueue.poll();
                    }else{
                        //如果还没有到时间，怎让线程阻塞等待
                        try {
                            //可以不做等待处理，但是会让线程一直去查看当前是否到达执行时间
                            //会浪费cpu资源，可以让其阻塞至指定时间
                            locker.wait(task.getTime() - curTime);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });
        thread.start();
    }
}

public class Demo2 {
    public static void main(String[] args) {

    }
}
